<?php


namespace app\api\controller;

use app\api\model\Book as BookMOdel;
use app\api\model\Comment as CommentModel;
use app\api\model\User as UserModel;

/***商品评论控制器
 * Class Comment
 * @package app\api\controller
 */
class Comment extends Base
{
    /***
     * Desc:获取商品评论
     * User: HAIYUN
     * Date: 2022/4/13 13:34
     */
    public function getCommentByBookId() {
        //校验参数
        $rules = [
            ['book_id','require','10001']
        ];
        $msg   = $this->validate($this->params, $rules);
        if ($msg !== true) $this->return_msg($msg, '参数错误');
        //查询评论
        $commentModel = new CommentModel();
        $return_list = [];
        $list = $commentModel->where('book_id',$this->params['book_id'])->order('create_time','desc')->select();
        foreach ($list as $k => $v){
            $return_list[$k]['id'] = $list[$k]['id'];//订单id
            $return_list[$k]['username'] = $list[$k]->user->nick_name;//用户名
            $return_list[$k]['avater'] = $list[$k]->user->avater;//用户名
            $return_list[$k]['content'] = $list[$k]['content'];//评论内容
            $return_list[$k]['create_time'] = $list[$k]['create_time'];//订单id
        }
        $this->return_msg('00000','查询该商品评论成功',$return_list);
    }

    /***
     * Desc:发表评论
     * User: HAIYUN
     * Date: 2022/4/13 13:58
     */
    public function leaveComment() {
        //根据token获取uid
        $uid = $this->getCurrentTokenVar("uid");
        //根据uid查找用户数据，判断是否存在
        $userModel = new UserModel();
        $user      = $userModel->where("id", $uid)->find();
        if (!$user) {
            $this->return_msg("20004", "用户不存在", []);
        }
        //校验参数
        $rules = [
            ['content', 'require', '10001'],
            ['book_id', 'require', '10001'],
            ['father_id', 'require', '10001'],
        ];
        $msg   = $this->validate($this->params, $rules);
        if ($msg !== true) $this->return_msg($msg, '参数错误');
        $commentModel = new CommentModel();
        //过滤不必要的参数
        $safe_data = $this->getDataByRule($this->params, $rules);
        $safe_data['user_id'] = $uid;
        $res = $commentModel->add($safe_data);
        if(!$res){
            $this->return_msg('20001','发表评论失败',[]);
        }else{
            $this->return_msg('00000','发表评论成功',$safe_data['content']);
        }
    }

}